package com.kadron.dao;

import java.util.List;

import javax.persistence.NoResultException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.UserKadrons;

@AutoCreate
@BypassInterceptors
@Name("userKadronsDAO")
@Scope(ScopeType.EVENT)
public class KUserKadronsDAO extends KDAO<UserKadrons> {

	@SuppressWarnings("unchecked")
	public List<UserKadrons> getAllUserKadrons(long userId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT e_ FROM UserKadrons e_ WHERE e_.user.id = :user_id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		return query.getResultList();
	}
	
	public Long getUserKadrons(long userId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT SUM(e_.kadrons) FROM UserKadrons e_ WHERE e_.user.id = :user_id GROUP BY e_.user.id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		try {
			return (Long) query.setMaxResults(1).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public Long getKadronsFromLastUpdate(long userId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT SUM(e_.kadrons) FROM UserKadrons e_ WHERE e_.user.id = :user_id AND e_.created > e_.user.statusUpdate GROUP BY e_.user.id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		try {
			return (Long) query.setMaxResults(1).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
}
